//
//  EassayViewController.m
//  HumorousScripts
//
//  Created by 李欢 on 15/6/15.
//  Copyright (c) 2015年 李欢. All rights reserved.
//

#import "EassayViewController.h"
#import "EassayTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "MJRefresh.h"
#import "DetialViewController.h"

#import "SANetWorkingTask.h"
#define Width [UIScreen mainScreen].bounds.size.width
#define Height [UIScreen mainScreen].bounds.size.height

@interface EassayViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * tableArray;
@property (nonatomic, assign) int i;
@end

@implementation EassayViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.i = 1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [SANetWorkingTask request:@"http://ic.snssdk.com/neihan/stream/mix/v1/?tag=joke&iid=2808558815&min_time=1434373034&message_cursor=0&count=30&content_type=-102&ac=WIFI&channel=tongbu&app_name=joke_essay&aid=7&version_code=4.1.0&device_platform=iphone&os_version=8.3&device_type=iPhone%205S&device_id=4272329077&vid=B06E994A-E093-479F-99E0-351D9340559F&openudid=e00e3962e37339ec7ce09708cad23b19b7a0693b&os_api=18&idfa=E2FD8DB1-FBA8-40EA-8C02-FAB446839AD1&screen_width=640" parmater:nil block:^(NSDictionary *result) {
//        NSMutableDictionary * dic = [result objectForKey:@"data"];
//        self.tableArray = [dic objectForKey:@"data"];
//        
//        [self creatView];
//
//
//    }];
    [self startConnection];
    
}

#pragma mark -
#pragma mark 请求数据
- (void)startConnection
{
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = @"http://ic.snssdk.com/neihan/stream/mix/v1/?tag=joke&iid=2808558815&min_time=1434373034&message_cursor=0&count=30&content_type=-102&ac=WIFI&channel=tongbu&app_name=joke_essay&aid=7&version_code=4.1.0&device_platform=iphone&os_version=8.3&device_type=iPhone%205S&device_id=4272329077&vid=B06E994A-E093-479F-99E0-351D9340559F&openudid=e00e3962e37339ec7ce09708cad23b19b7a0693b&os_api=18&idfa=E2FD8DB1-FBA8-40EA-8C02-FAB446839AD1&screen_width=640";
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic1 = [dic objectForKey:@"data"];
        NSArray *array1 = [dic1 objectForKey:@"data"];
        for (NSDictionary *dic in array1) {
            if ([dic objectForKey:@"group"] != nil) {
                [self.tableArray addObject:dic];
            }
        }
        NSLog(@"%ld", self.tableArray.count);
        
        [self creatView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        
    }];
    
}


//创建tableView
-(void)creatView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width , self.view.frame.size.height - 64/667.0*Height) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellStyleDefault;
    
    //设定上啦加载 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:self.tableView];
    
}
//下拉刷新点击事件
- (void)loadNewData:(id)sender
{
    //    self.i = 2;
        [self.tableArray removeAllObjects];
        [self.tableView reloadData];
    
    [self startConnection];
    [self.tableView.header endRefreshing];
}
//上啦加载点击事件
- (void)loadMoreData
{
    //网络请求 page值 i++
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = [NSString stringWithFormat:@"http://ic.snssdk.com/neihan/stream/mix/v1/?tag=joke&iid=2808558815&min_time=1434373034&message_cursor=%d" , self.i];
    
    NSString *str1 = @"&count=30&content_type=-102&ac=WIFI&channel=tongbu&app_name=joke_essay&aid=7&version_code=4.1.0&device_platform=iphone&os_version=8.3&device_type=iPhone%205S&device_id=4272329077&vid=B06E994A-E093-479F-99E0-351D9340559F&openudid=e00e3962e37339ec7ce09708cad23b19b7a0693b&os_api=18&idfa=E2FD8DB1-FBA8-40EA-8C02-FAB446839AD1&screen_width=640";
    NSString *str3 = [NSString stringWithFormat:@"%@%@",str,str1];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    [m GET:str3 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic1 = [dic objectForKey:@"data"];
        NSArray *array1 = [dic1 objectForKey:@"data"];
        for (NSDictionary *dic in array1) {
            if ([dic objectForKey:@"group"] != nil) {
                [self.tableArray addObject:dic];
            }
        }
        NSLog(@"%ld", self.tableArray.count);
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        
    }];
    
    // 拿到当前的上拉刷新控件，结束刷新状态
    
    self.i += 1;
    [self.tableView.footer endRefreshing];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString * cellIdentify = @"cell";
    EassayTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[EassayTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSDictionary * Dic = [self.tableArray objectAtIndex:indexPath.row];
    NSDictionary * comDic = [Dic objectForKey:@"group"];
    NSDictionary * uesrDic = [comDic objectForKey:@"user"];
//    头像
    [cell.imageview sd_setImageWithURL:[uesrDic objectForKey:@"avatar_url"] placeholderImage:nil];
//    姓名
    cell.alabel.text = [uesrDic objectForKey:@"name"];
    [cell.LastView.lable1 setText:[NSString stringWithFormat: @"%@",[comDic objectForKey:@"digg_count"] ]];
    cell.LastView1.lable1.text = [NSString stringWithFormat:@"%@",[comDic objectForKey:@"bury_count"] ];
    cell.LastView2.lable1.text = [NSString stringWithFormat:@"%@",[comDic objectForKey:@"comment_count"]];
    cell.share = [comDic objectForKey:@"share_url"];
    
//    内容
    NSDictionary * gDic = [self.tableArray objectAtIndex:indexPath.row];
    NSDictionary * sgDic = [gDic objectForKey:@"group"];
    cell.label.text = [sgDic objectForKey:@"content"];
//    自使用高度
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [cell.label.text boundingRectWithSize:CGSizeMake(335, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    cell.y = rect.size.height;
    [cell setAlabelFrame];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * gDic = [self.tableArray objectAtIndex:indexPath.row];
    NSDictionary * sgDic = [gDic objectForKey:@"group"];
    NSString *str = [sgDic objectForKey:@"content"];
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [str boundingRectWithSize:CGSizeMake(335, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height  + 90 + 30 + 40 ;
}

#pragma mark -
#pragma mark 点击协议

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * gDic = [self.tableArray objectAtIndex:indexPath.row];
    NSDictionary * sgDic = [gDic objectForKey:@"group"];
    NSDictionary * uesrDic = [sgDic objectForKey:@"user"];
    
    
    


    DetialViewController * detail = [[DetialViewController alloc]init];
    detail.groupId = [sgDic objectForKey:@"group_id"];
    detail.share = [sgDic objectForKey:@"content"];
    
    detail.pic = [uesrDic objectForKey:@"avatar_url"];
    detail.name = [uesrDic objectForKey:@"name"];
    detail.lable1 = [NSString stringWithFormat: @"%@",[sgDic objectForKey:@"digg_count"] ];
    detail.lable2 = [NSString stringWithFormat:@"%@",[sgDic objectForKey:@"bury_count"] ];
    detail.lable3 = [NSString stringWithFormat:@"%@",[sgDic objectForKey:@"comment_count"]];
    
    [self.navigationController pushViewController:detail animated:YES];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
